package backend_agent

import (
	"context"
	"github.com/jinzhu/copier"
	"xialou_platform/app/requestx"
	"xialou_platform/app/respx"
	"xialou_platform/app/tools"
	"xialou_platform/services/agent/rpc/agentClient"
	"xialou_platform/services/wallet/rpc/walletClient"

	"xialou_platform/services/agent/api/internal/svc"
	"xialou_platform/services/agent/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AgentLevelListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAgentLevelListLogic(ctx context.Context, svcCtx *svc.ServiceContext) AgentLevelListLogic {
	return AgentLevelListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AgentLevelListLogic) AgentLevelList(req *types.AgentLevelListReq) (resp *respx.PageResp, err error) {

	agentId := respx.IDParse(req.AgentId).GetInt64()
	if agentId == 0 {
		uid, err := requestx.FetchUserIdByJwt(l.ctx)
		if err != nil {
			return nil, err
		}
		agentId = uid
	}
	child, err := l.svcCtx.AgentRpc.AgentChild(l.ctx, &agentClient.AgentChildReq{
		Page:      req.Page,
		PageSize:  req.PageSize,
		ParentUid: agentId,
	})
	data := make([]*types.AgentChildDataListResp, 0)
	for _, v := range child.List {
		var c types.AgentChildDataListResp
		err := copier.Copy(&c, v)
		if err != nil {
			continue
		}
		if len(v.RealName) > 0 {
			c.Name = v.RealName
		}
		c.Id = respx.IDFrom(v.Id).ToString()
		c.CreateTime = tools.TimeUnixShowLayoutString(v.CreateTime)

		// 查询商家数量
		storeCount, err := l.svcCtx.AgentRpc.StoreCount(l.ctx, &agentClient.StoreCountReq{AgentId: v.Id})
		if err != nil {
			return nil, err
		}
		c.StoreNum = storeCount.Count

		profit, err := l.svcCtx.WalletRpc.AgentProfit(l.ctx, &walletClient.AgentProfitReq{
			AgentId: v.Id,
		})
		if err != nil {
			return nil, err
		}
		c.CardNum = profit.CardNum
		c.CardProfit = profit.CardProfit
		c.GroupProfit = profit.GroupProfit
		c.PayProfit = profit.PayProfit
		data = append(data, &c)

	}
	if err != nil {
		return nil, err
	}
	return respx.NewPageResp(req.Page, req.PageSize, child.Total, data), nil
}
